package cn.xiyun.xiyuncc.MQ.transactionListener;

import cn.xiyun.xiyuncc.domain.CourseOrder;
import cn.xiyun.xiyuncc.dto.Order2PayDto;
import cn.xiyun.xiyuncc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@RocketMQTransactionListener(txProducerGroup = "createOrder-message-group")
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object age) {
        CourseOrder courseOrder = JSON.parseObject(JSON.toJSONString(age), CourseOrder.class);
        try {
            courseOrderService.insertOrder(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception exception) {
            exception.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }


    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        Order2PayDto order2PayDto = JSON.parseObject(message.toString(), Order2PayDto.class);
        String orderNo = order2PayDto.getOrderNo();
        System.out.println(order2PayDto);
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        CourseOrder courseOrder1 = courseOrderService.selectOne(wrapper);

        if (courseOrder1 != null) {
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
